﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SliderAnim : MonoBehaviour {

    public Slider loadingSlider;

    public Text loadingProgressText;

    // Use this for initialization
    void Start () {
		
    }

    public void ResetAnim()
    {
        SetSliderValue(0);
    }

    public void PlaySlider(float time,Action onEnd)
    {
        DoActionDelay.DelayAction(time, () =>
        {
            onEnd?.Invoke();
        });
        
        if(gameObject.activeInHierarchy)
            StartCoroutine(PlaySlider(time));
    }
    
    public IEnumerator PlaySlider(float time)
    {
        float initValue = loadingSlider.value;

        float timer = 0;
        while (timer < time)
        {
            timer += Time.deltaTime;
            float rate = timer / time;
            float value = Mathf.Lerp(initValue, 1, rate);

            SetSliderValue(value);

            yield return null;
        }
    }

    public void SetSliderValue(float value)
    {
        value = value < 0.07f ? 0.07f : value;
        if (loadingSlider)
            loadingSlider.value = value;

        if (loadingProgressText)
            loadingProgressText.text = string.Format("{0:P1}", value);
    }


    // Update is called once per frame
    void Update () {
		
    }
}